<?php
/**
 * 返回参数格式化
 */

namespace backend\component;


class ResultFormat
{
    private $status = 1;   //1正常，0错误
    private $msg = "操作成功";
    private $data = [];

    const RESULT_JSON = 1;
    const RESULT_ARRAY = 2;

    private static $_instance = null;

    private function __construct()
    {
    }

    private static function getInstance() {
        if (self::$_instance == null) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 设置错误
     * @param $msg
     * @return mixed
     */
    public static function error($msg,$resultType=self::RESULT_JSON) {
        $obj = self::getInstance();
        $obj->status = 0;
        $obj->msg = $msg;
        return $resultType==self::RESULT_JSON ? $obj->toJson() : $obj->toArray();
    }

    /**
     * 设置成功
     * @return mixed
     */
    public static function success($msg,$data="",$resultType=self::RESULT_JSON) {
        $obj = self::getInstance();
        $obj->status = 1;
        $obj->msg = $msg;
        if (!empty($data)) {
            $obj->data = $data;
        }
        return $resultType==self::RESULT_JSON ? $obj->toJson() : $obj->toArray();
    }

    /**
     * 返回json
     */
    public function toJson() {
        return json_encode($this->toArray());
    }


    /**
     * 返回数组
     */
    public function toArray() {
        return ["status"=>$this->status,"msg"=>$this->msg,"data"=>$this->data];
    }
}